package com.slkj.Realm;


import com.slkj.entity.Userinfo;
import com.slkj.service.UserService;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    Logger log = LoggerFactory.getLogger(UserRealm.class);

    /**
     * 提供帐户信息，返回认证信息
     *
     * @param authenticationToken
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();
        log.info("---------------------->>用户" + username + "开始登陆");
        Userinfo userinfo = userService.findUserinfoByUsername(username);
        if (userinfo == null) {
            log.error("用户不存在");
            throw new UnknownAccountException("用户不存在");
        }
        //这句是我加的
        SecurityUtils.getSubject().getSession().setAttribute("userinfo",userinfo);

        return new SimpleAuthenticationInfo(userinfo.getUsername(), userinfo.getPassword(), ByteSource.Util.bytes(username),
                this.getName());
    }

    /**
     * 提供用户信息，返回权限信息
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }
}
